package com.sahadev.mvp.other;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

/**这就是我们的IView的实现类了
 * Created by Sahadev on 2015/11/12.
 */
public abstract class BaseRecyclerAdapter<T extends BaseRecyclerViewHolder> extends android.support.v7.widget.RecyclerView.Adapter<T> {
    protected List lists = new ArrayList();
    private LayoutInflater inflate;

    public BaseRecyclerAdapter(Context context) {
        inflate = LayoutInflater.from(context);
    }

    /**添加数据
     * @param index
     * @param lists
     */
    public void addData(int index, List lists) {
        if (index == 0)
            this.lists = lists;
        else
            this.lists.addAll(lists);
//            notifyItemRangeInserted(this.lists.size() - lists.size(), lists.size());
        notifyDataSetChanged();
    }

    @Override
    public int getItemCount() {
        return lists.isEmpty() ? 20 : lists.size();
    }//20是为了这里有示例数据

    /**该方法不需要重新，直接会创建好
     * @param viewGroup
     * @param i
     * @return
     */
    @Override
    final public T onCreateViewHolder(ViewGroup viewGroup, int i) {
        Class<? extends BaseRecyclerViewHolder> viewHolderClass = getViewHolderClass();
        try {
            Constructor<? extends BaseRecyclerViewHolder> constructor = viewHolderClass.getConstructor(View.class);
            return (T) constructor.newInstance(inflate.inflate(getInstanceLayoutRes(), null));
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**由子类自由绑定
     * @param viewHolder
     * @param i
     */
    @Override
    public abstract void onBindViewHolder(T viewHolder, int i);

    /**获取ViewHolder的类.它被用来自动实例化
     * @return
     */
    protected abstract Class<? extends BaseRecyclerViewHolder> getViewHolderClass();

    /**获取要实例化的布局的id
     * @return
     */
    protected abstract int getInstanceLayoutRes();
}
